<?php
namespace App\Admin\Controller;

use App\Common\Logic\FileLogic;
use Hyperf\Di\Annotation\Inject;
use App\Admin\Validate\AdminValidate;
use App\Common\Controller\AbstractController;
use App\Server\Model\Admin;
use App\Server\Model\AdminGroup;
use Hyperf\Utils\Context;

class AdminController extends AbstractController
{

    /**
     * @Inject()
     * @var AdminValidate
     */
    protected $AdminValidate;

    /**
     * 管理员列表
     * @return [type] [description]
     */
    public function index()
    {
        $page = $this->request->query('page');
        if ($page){
            //实例化管理员模型
            $model = new Admin();
            $param = $this->request->all();
            $where = [];
            if(!empty($param['keywords'])) {
                $unity_search[] = ['nickname',$param['keywords']];
                $unity_search[] = ['name',$param['keywords']];
                $where['unity_search'] = $unity_search;
            }
            $admin = $model->getListPage($where,['*'],'created_at desc');
            $adminGroup = new AdminGroup();
            $adminGroupData = $adminGroup->getList([],['id','title']);
            $adminGroupData = array_column($adminGroupData,null,'id');
            foreach ($admin['data'] as &$val){
                if (!empty($val['groups'])){
                    $groupIds = explode(',',$val['groups']??'');
                    foreach($groupIds as $val_id){
                        if (empty($val['groupName'])){
                            $val['groupName'] = $adminGroupData[$val_id]['title'];
                        }else{
                            $val['groupName'] = $val['groupName'].'|'.$adminGroupData[$val_id]['title'];
                        }
                    }
                }else{
                    $val['groupName'] = '';
                }
            }

            return $this->success($admin['data'], '成功', ['count'=>$admin['total']]);
        }

        return $this->render->render('/admin/admin/index');
    }

    public function delete()
    {
        $admin = new Admin();
        $adminInfo = Context::get('adminInfo');

        $id    = $this->request->query('id');
        if(!$id) {
            $this->error('缺少必要条件');
        }
        if ($id == $adminInfo['id']){
            $this->error('不能删除自身账号');
        }
        if ($id == 1) {
            $this->error('系统拥有者，无法删除！');
        }
        $deleteRes = $admin->dataDelete([['id','=',$id]]);
        return $this->success([],'删除成功');
    }


    public function add()
    {
        $admin = new Admin();
        $adminGroup = new AdminGroup();
        if($this->request->getMethod()=='POST')
        {
            $param = $this->request->all();
            $errorMessage = $this->AdminValidate->add($this->request);
            //验证部分数据合法性
            if ($errorMessage) {
                return $this->error('提交失败：' . $errorMessage);
            }

            if(!empty($param['password'])) {
                //重置密码
                if(empty($param['password_confirm']) or $param['password_confirm'] !== $param['password']) {
                    return $this->error('两次密码不一致');
                }
                $param['password']  = password($param['password']);
            } else {
                unset($param['password']);
            }

            $param['groups']      = implode(',',$param['group_id']);
            unset($param['group_id']);
            unset($param['file']);
            unset($param['password_confirm']);
            $param['created_at'] = $param['updated_at'] = time();

            $updateRes = $admin->dataAdd($param);
            if ($updateRes){
                return $this->success([],'添加成功');
            }else{
                return $this->error('添加失败');
            }
        }
        else
        {
            $data = [];
            $data['group'] = $adminGroup->getList([['status','=',1]],['id','title']);
            return $this->render->render('/admin/admin/add', $data);
        }

    }


    public function edit()
    {
        $admin = new Admin();
        $adminGroup = new AdminGroup();
        $adminInfo = Context::get('adminInfo');
        if($this->request->getMethod()=='POST')
        {
            $param = $this->request->all();
            $errorMessage = $this->AdminValidate->edit($this->request);
            //验证部分数据合法性
            if ($errorMessage) {
                return $this->error('提交失败：' . $errorMessage);
            }

            // 不允许其他管理员修改id=1的管理员
            if($param['id'] == 1 and $adminInfo['id'] !== 1)
            {
                return $this->error('不允许其他人修改系统所有者');
            }

            unset($param['name']);
            if(!empty($param['password'])) {
                //重置密码
                if(empty($param['password_confirm']) or $param['password_confirm'] !== $param['password']) {
                    return $this->error('两次密码不一致');
                }
                $param['password']  = password($param['password']);
            } else {
                unset($param['password']);
            }
            unset($param['file']);
            unset($param['password_confirm']);
            $param['groups']      = implode(',',$param['group_id']);
            unset($param['group_id']);
            $param['updated_at'] = time();

            $updateRes = $admin->dataUpdate([['id','=',$param['id']]], $param);
            if ($updateRes){
                return $this->success([],'修改成功');
            }else{
                return $this->error('修改失败');
            }
        }
        else
        {
            $id = $this->request->query('id');
            $getData = $admin ->getCacheInfo([['id','=',$id]], 'admin_info_id_'.$id);
            $data = [];
            $data['data'] = $getData;
            $data['group'] = $adminGroup->getList([['status','=',1]],['id','title']);
            return $this->render->render('/admin/admin/edit', $data);
        }
    }


    public function editadmininfo()
    {
        $admin = new Admin();
        $adminInfo = Context::get('adminInfo');
        if($this->request->getMethod()=='POST')
        {
            $param = $this->request->all();
            $errorMessage = $this->AdminValidate->editadmininfo($this->request);
            //验证部分数据合法性
            if ($errorMessage) {
                return $this->error('提交失败：' . $errorMessage);
            }

            // 不允许其他管理员修改id=1的管理员
            if($param['id'] == 1 and $adminInfo['id'] !== 1)
            {
                return $this->error('不允许其他人修改系统所有者');
            }

            unset($param['name']);
            if(!empty($param['password'])) {
                //重置密码
                if(empty($param['password_confirm']) or $param['password_confirm'] !== $param['password']) {
                    return $this->error('两次密码不一致');
                }
                $param['password']  = password($param['password']);
            } else {
                unset($param['password']);
            }
            unset($param['file']);
            unset($param['password_confirm']);
            $param['updated_at'] = time();

            $updateRes = $admin->dataUpdate([['id','=',$param['id']]], $param);
            if ($updateRes){
                return $this->success([],'修改成功');
            }else{
                return $this->error('修改失败');
            }
        }
        else
        {
            $data = [];
            $data['admin'] = $adminInfo;
            return $this->render->render('admin/admin/edit_admin_info',$data);
        }
    }

    
    /**
     * 管理员个人资料修改，属于无权限操作，仅能修改昵称和头像，后续可增加其他字段
     * @return [type] [description]
     */
    public function personal()
    {
        //获取管理员id
        $adminInfo = Context::get('adminInfo');
        $id = $adminInfo['id'];
        $model = new Admin();
        if($id > 0) {
            //是修改操作
            if($this->request->getMethod()=='POST') {
                //是提交操作
                $post = $this->request->post();
                //验证昵称是否存在
                $where=[];
                $where[]=['nickname','=',$post['nickname']];
                $where[]=['id','neq',$post['id']];
                $nickname = $model->getList($where,'id');
                if(!empty($nickname)) {
                    return $this->error('提交失败：该昵称已被占用');
                }
                $data[]=$post;
                if(false == $model->dataSave($data,['id'=>$id],true,true,'one')) {
                    return $this->error('修改失败');
                } else {
                    addlog($model->id);//写入日志
                    return $this->success('修改个人信息成功','admin/admin/personal');
                }
            } else {
                //非提交操作
                $info['admin'] = $model -> getCacheInfo([['id','=',$id]], 'admin_info_id_'.$id);
                $data['info'] = $info;
                return $this->render->render('admin/personal',$data);
            }
        } else {
            return $this->error('id不正确');
        }
    }




    /**
     * 修改密码
     * @return [type] [description]
     */
    public function editPassword()
    {
        $getRes = $this->request->all();
        $id = !empty($getRes['id']) ? $getRes['id'] : 0;
    	if($id > 0) {
            $model = new Admin();
    		if($id == Session::get('admin')) {
    			$post = $this->request->post();
    			//验证  唯一规则： 表名，字段名，排除主键值，主键名
	            $validate = new \think\Validate([
	                'password' => 'require|confirm',
	                'password_confirm' => 'require',
	            ]);
	            //验证部分数据合法性
	            if (!$validate->check($post)) {
	                $this->error('提交失败：' . $validate->getError());
	            }
	            $where = [];
	            $where[] =['id','=',$id];
    			$admin = $model -> getInfo($where , 'password');
    			if(password($post['password_old']) == $admin['password']) {
    				if(false == $model -> dataUpdate($where,['password'=>password($post['password'])])) {
    					return $this->error('修改失败');
    				} else {
                        addlog($this->request);//写入日志
    					return $this->success('修改成功','admin/main/index');
    				}
    			} else {
    				return $this->error('原密码错误');
    			}
    		} else {
    			return $this->error('不能修改别人的密码');
    		}
    	} else {
            $adminInfo = Context::get('adminInfo');
            $id = $adminInfo['id'];
            $data['id'] = $id;
            return $this->render->render('admin/edit_password',$data);
    	}
    }

}
